<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use OSS\OssClient;
use OSS\Core\OssException;
use Symfony\Component\HttpFoundation\File\Exception\FileException;


class UploadController extends Controller
{
    public function uploadImages(Request $request)
    {
        $user_id = $request->session()->get("user_id");
        if(!$user_id){
            $user_id = "admin";
        }
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            try {
                $ossClient = new OssClient(
                    config('UEditorUpload.core.oss.accessKeyId'),
                    config('UEditorUpload.core.oss.accessKeySecret'),
                    config('UEditorUpload.core.oss.endpoint'),true);
                //获得文件类型
                $type='.'.$image->getClientOriginalExtension();
                $this->fileType=$type;//设置UEditor的文件类型
                //生成随机文件名
                $object=substr(str_shuffle("qwertyuiopasdfghjklzxcvbnm0123456789"),0,20).time();
                $object=$user_id.'/'.$object.$type;//拼接到后戳名的文件名
                $this->fullName=$object;//设置UEditor的文件名
                try{
                    //上传文件  (ALIOSS_BUCKET 填自己的BUCKET名)
                    $res = $ossClient->uploadFile(
                        config('UEditorUpload.core.oss.bucket'),
                        config('UEditorUpload.core.oss.imagedir').$object,
                        $image->getPathName());
                    if(isset($res['oss-request-url'])){
                        return response()->json(['status' => 0, 'path' => $res['oss-request-url']]);
                    }

                }catch (OssException $e){
                    //设置错误消息为未知错误
                    echo '1';
                    return false;
                }



            } catch (FileException $exception) {
                $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
                return false;
            }
        }


    }
    /**
     * 获取用户指定文件夹下的图片列表
     * api 文档 https://www.alibabacloud.com/help/zh/doc-detail/32105.htm?spm=a2c63.p38356.b99.233.cbd54d91085ycm
     */
    public function getUserImages(Request $request)
    {
        $user_id = $request->session()->get("user_id");
        if(!$user_id){
            $user_id = "admin";
        }
        $return = $new = [];
        $prefix = 'upload/image/'.$user_id.'/';
        $delimiter = '/';
        $nextMarker = '';
        $maxkeys = 30;
        $bucket = config('UEditorUpload.core.oss.bucket');
        try {
            $options = array(
                'delimiter' => $delimiter,
                'prefix' => $prefix,
                'max-keys' => $maxkeys,
                'marker' => $nextMarker,
            );
            $ossClient = new OssClient(
                config('UEditorUpload.core.oss.accessKeyId'),
                config('UEditorUpload.core.oss.accessKeySecret'),
                config('UEditorUpload.core.oss.endpoint'),true);

            $listObjectInfo = $ossClient->listObjects($bucket, $options);
            $listObject = $listObjectInfo->getObjectList();

            foreach ($listObject as $key=>$value){
                $return[$key]['url']  = 'http://'.$bucket.'.oss-cn-hangzhou.aliyuncs.com/'.$value->getKey();
                $return[$key]['key']  = $value->getKey();
                $return[$key]['eTag'] = $value->getETag();
                $return[$key]['lastModified'] = $value->getLastModified();
                $return[$key]['size'] = $value->getSize();
                $return[$key]['storageClass'] = $value->getStorageClass();
                $return[$key]['type'] = $value->getType();
            }
            return $return;
        } catch (\Exception  $exception) {
            $this->stateInfo = $this->getStateInfo(__FUNCTION__ . ": FAILED\n");
            $this->stateInfo = $this->getStateInfo($exception->getMessage());
            return false;
        }
    }
    /**
     * 删除object
     *
     * @param OssClient $ossClient OSSClient实例
     * @param string $bucket bucket名字
     * @return null
     */
    function deleteObject($object)
    {
        // $object = "oss-php-sdk-test/upload-test-object-name.txt";
        $bucket = config('UEditorUpload.core.oss.bucket');
        try{
            $ossClient = new OssClient(
                config('UEditorUpload.core.oss.accessKeyId'),
                config('UEditorUpload.core.oss.accessKeySecret'),
                config('UEditorUpload.core.oss.endpoint'),true);

            $delete = $ossClient->deleteObject($bucket, $object);
            if (preg_match('/^[2]\d{2}$/',$delete['info']['http_code'])){
                return response()->json(['code'=>0,'message'=>'Success']);
            }else{
                throw new OssException('Error');
            }
        } catch(OssException $e) {
            return response()->json(['code'=>$e->getErrorCode(),'message'=>$e->getErrorMessage()]);
        }
    }
    
    // 文件上传方法
    public function uploadFile(Request $request)
    {
        
        $file = $request->file('file');
        
        // 文件是否上传成功
        if ($file->isValid()) {
            
            // 获取文件相关信息
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = $file->getClientOriginalExtension();     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            $type = $file->getClientMimeType();     // image/jpeg
            
            // 上传文件
            $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
            // 使用我们新建的uploads本地存储空间（目录）
            $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
            var_dump($bool);
            
        }
    }
}
